package com.lsfb.signsys.compatible;


import com.google.common.base.Strings;
import com.lsfb.signsys.utils.Utils;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;

import okhttp3.Headers;
import okhttp3.Request;

/**
 * Created by zgscwjm on 16/1/16.
 */
public class Token {


    public static Request getToken(String url, Request request) {
        Request.Builder builder = request.newBuilder();
        getToken(url, builder);
        request = builder.build();
        return request;
    }

    /**
     * 获得带token的url地址
     *
     * @param url url地址
     * @return 获得带token的url地址
     * @author zgscwjm
     * @time 2015年10月10日-下午4:02:46
     */


    public static void getToken(String url, Request.Builder builder) {
        Date date = new Date();
        SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd-HH");
        String temp3 = "";

        if (Config.TOKENTYPE == 1) {
            SimpleDateFormat dateformats = new SimpleDateFormat("HH-mm");
            temp3 = dateformats.format(date);

        } else {
            temp3 = String.valueOf(date.getTime() / 1000);
        }


        String temp1 = Config.Net_Token_Prefix;

        try {
            temp1 = temp1 + dateFormat.parse(dateFormat.format(date)).getTime() / 1000;
        } catch (ParseException e) {
            e.printStackTrace();
        }
        temp1 = temp1 + Config.Net_Token_Suffix + url.substring(url.lastIndexOf("/") + 1);
        if (!Strings.isNullOrEmpty(Config.getUserId())) {
            temp1 = temp1 + "-" + Config.getUserId();
            builder.addHeader("userId", Config.getUserId());
        }
        builder.addHeader("token", MD5.GetMD5Code(MD5.GetMD5Code(temp1)));
        builder.addHeader("times", temp3);
        builder.addHeader("version", Config.getVERSION());
    }


}
